package com.chenchao.net;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/24 20:44
 * @Author : Chen Chao
 * @File : javaSE.com.chenchao.net.Test05S.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 * 多线程上传服务端
 */
public class Test05S implements Runnable {
    public static ServerSocket serverSocket;
     Socket  accept;

    static {
        try {
            /*创建对象*/
            serverSocket = new ServerSocket(8080);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        int i=0;
        while (i<5){
            /*获取socket*/
            Test05S test05S = new Test05S();
            test05S.accept=Test05S.serverSocket.accept();
            /*当有接收到socket时开新线程*/
            new Thread(test05S).start();
            System.out.println(i+++"次上传成功");
        }
    }

    @Override
    public void run() {
        try {
            /*获取传入的图像*/
            InputStream inputStream = accept.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            File file =new File("myjava01/src/fo",
                    new Random().nextInt(100)+"gg.jpg");
            FileOutputStream outputStream = new FileOutputStream(file);
            while ((len=inputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
            }

            /*返回上传结果*/
            OutputStream ops = accept.getOutputStream();
            ops.write("上传成功".getBytes());

            /*关闭资源*/
            accept.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
